/*
 *
 *  Copyright (C) 2010 Tal Eisenberg
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package tal.drivechain.matchers;

import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import tal.drivechain.chain.ChainNode;
import tal.drivechain.variable.Variable;
import tal.drivechain.variable.types.DataType;

/**
 *
 * @author Main
 */
public class StringMatcher extends ValueMatcher {
    Pattern pattern;
            
    @Override
    protected void parseSpecial(String pattern) throws IllegalArgumentException {
        String spattern = (String)Variable.parseVarValue("name", DataType.STRING, pattern).getValue(null);
        try {
            this.pattern = Pattern.compile(spattern);
        } catch (PatternSyntaxException pe) {
            throw new IllegalArgumentException("Invalid regex pattern syntax: " + pe.getMessage());
        }
    }

    @Override
    protected boolean matchSpecial(Object value, ChainNode context) throws IllegalArgumentException {
        return pattern.matcher((String)value).matches();
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof StringMatcher) {
            if (super.equals(obj)) return true;
            else {
                StringMatcher that = (StringMatcher)obj;
                return (this.pattern.equals(that.pattern));
            }
        } else return false;
    }

    @Override
    public String toString() {
        return "'" + pattern.toString() + "'";
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 29 * hash + (this.pattern != null ? this.pattern.hashCode() : 0);
        return hash;
    }
}
